package lambda;

import java.util.concurrent.RecursiveTask;

/**
 * @author : 李红磊
 * @version :1.0
 * @date : 2021/10/9 15:26
 * @description : ForkJoin
 */
public class ForkJoinCalculate extends RecursiveTask<Long> {

    long start;
    long end;

    public static final int THREAHORD = 10000;


    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {

        if (end - start < THREAHORD) {
            long sum = 0;
            for (long i = start; i <= end; i++) {

                sum = sum + i;
            }

            return sum;

        } else {

            long middle = end + start >>> 1;
            ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
            left.fork();//拆分成子任务，压入线程队列

            ForkJoinCalculate right = new ForkJoinCalculate(middle + 1, end);
            right.fork();


            return left.join() + right.join();
        }


    }


}
